﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;
using System.Globalization;

namespace Shuba.Web.master
{
    public partial class branch_plan_list : basePage
    {
        Int64 TargetAmount = 0, TargetNoa = 0, TargetAmountReal = 0, TargetNoaReal = 0;
        string msg = "";
        string ClusterID, TargetYear, RegionID;
        bool IsView = false, IsAdd = false, IsEdit = false, IsDelete = false, IsChecker = false;

        private void BindData()
        {
            Shuba.Business.BranchTarget _BranchTarget = new Shuba.Business.BranchTarget();
            List<BranchTargetInfo> list;

            TargetYear = ddlYear.Text;
            ClusterID = ddlCluster.SelectedValue.ToString();

            list = _BranchTarget.GetListByCluster(ClusterID, TargetYear);

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchTargetInfo> comparer = new DynamicComparer<BranchTargetInfo>(sort);
                list.Sort(comparer);
            }

            gvList.DataSource = list;
            gvList.DataBind();

            lblAmountBranch.Text = TargetAmount.ToString("N0");
            lblNoaBranch.Text = TargetNoa.ToString("N0");

            lblAmountBranchReal.Text = TargetAmountReal.ToString("N0");
            lblNoaBranchReal.Text = TargetNoaReal.ToString("N0");

            Shuba.Business.ClusterTarget _ClusterTarget = new Shuba.Business.ClusterTarget();
            Shuba.Model.ClusterTargetInfo bi;

            bi = _ClusterTarget.Get(ClusterID, TargetYear);

            lblYear.Text = TargetYear;
            lblCluster.Text = ddlCluster.SelectedItem.Text;

            lblAmount.Text = bi.TargetAmount.ToString("N0");
            lblNoa.Text = bi.Noa.ToString("N0");
            lblAmountReal.Text = bi.TargetAmountReal.ToString("N0");
            lblNoaReal.Text = bi.NoaReal.ToString("N0");

            HidRegionID.Value = ddlRegion.SelectedValue;
            HidClusterID.Value = ClusterID;
            HidTargetYear.Value = TargetYear;

            //if (IsEdit) gvList.Columns[5].Visible = true; else gvList.Columns[5].Visible = false;
            if (!IsView) gvList.Columns[7].Visible = false;
            
            
            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();

                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("TARGET_BRANCH");
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = this.GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                InitYearList();
                InitRegionList();
                InitClusterList(ddlRegion.SelectedValue);

                ddlYear.SelectedIndex = ddlYear.Items.IndexOf(ddlYear.Items.FindByValue(ProcessingDate().Year.ToString()));

                InitSort();
                BindData();

                LabelTitle.Text = GetPageTitle("TARGET_BRANCH");

            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            TargetYear = ddlYear.SelectedValue;
            RegionID = ddlRegion.SelectedValue;
            ClusterID = ddlCluster.SelectedValue;

            string url = "branch_plan_add.aspx" + "?yr=" + TargetYear + "&reg=" + RegionID + "&clus=" + ClusterID;

            Response.Redirect(url);
        }
        
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }

        protected void InitYearList()
        {
            Int32 NextYear = Convert.ToInt32(ProcessingDate().Year.ToString()) + 4;
            Int32 LastYear = Convert.ToInt32(ProcessingDate().Year.ToString()) - 1;

            for (var n = LastYear; n < NextYear; n++)
            {
                ddlYear.Items.Add(n.ToString());
            }
        }

        protected void gvList_RowCommand(Object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "View":
                    Response.Redirect("branch_plan_add.aspx?a=vw&id=" + e.CommandArgument + "&yr=" + HidTargetYear.Value + "&reg=" + HidRegionID.Value + "&clus=" + HidClusterID.Value);
                    break;
                case "Edit":
                    Response.Redirect("branch_plan_add.aspx?a=ed&id=" + e.CommandArgument + "&yr=" + HidTargetYear.Value + "&reg=" + HidRegionID.Value + "&clus=" + HidClusterID.Value);
                    break;
                //case "Remove":
                //    string id = e.CommandArgument.ToString();
                //    Shuba.Business.BranchTarget _BranchTarget = new Shuba.Business.BranchTarget();
                //    Shuba.Model.BranchTargetInfo _bi = _BranchTarget.Get(id, lblYear.Text);
                //    _bi.UpdateBy = HttpContext.Current.User.Identity.Name;
                //    _bi.UpdateDate = ProcessingDate();
                //    _bi.ActType = "DELETE";
                //    try
                //    {
                //        _BranchTarget.Save(_bi);
                //        AddLog("DELETE", "DELETE BRANCH TARGET PLAN");
                //    }
                //    catch (Exception ex)
                //    {
                //        ErrBox.Visible = true;
                //        ErrMsg.Text = ex.Message;
                //    }
                //    RestartPage();
                //    break;
            }
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression,e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;
            BindData();
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string Amount, Noa, AmountReal, NoaReal;

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnEdit = (LinkButton)e.Row.FindControl("btnEdit");
                LinkButton btnView = (LinkButton)e.Row.FindControl("btnView");

                Amount = e.Row.Cells[3].Text.Replace(",", "").Trim();
                Noa = e.Row.Cells[4].Text.Replace(",", "").Trim();

                AmountReal = e.Row.Cells[5].Text.Replace(",", "").Trim();
                NoaReal = e.Row.Cells[6].Text.Replace(",", "").Trim();

                TargetAmount += Convert.ToInt64(Amount);
                TargetNoa += Convert.ToInt64(Noa);
                TargetAmountReal += Convert.ToInt64(AmountReal);
                TargetNoaReal += Convert.ToInt64(NoaReal);

                if (IsAdd || IsEdit)
                {
                    btnEdit.Enabled = true;
                    btnView.Enabled = true;
                }
                else
                {
                    btnView.Enabled = true; 
                    btnEdit.Enabled = false;
                }
            }
        }

        /*======================================
                APPROVAL GRID START HERE
         =======================================
         */
        private void BindApprovalData()
        {
            Shuba.Business.BranchTarget _BranchTarget = new Shuba.Business.BranchTarget();
            List<BranchTargetInfo> list;

            list = _BranchTarget.GetListApproval(ddlYear.Text, HttpContext.Current.User.Identity.Name, Session["UnitID"].ToString());
            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<BranchTargetInfo> comparer = new DynamicComparer<BranchTargetInfo>(sort);
                list.Sort(comparer);
            }
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;
            BindApprovalData();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                string branch = ApprovalGrid.DataKeys[row.RowIndex].Values["BranchID"].ToString();
                string year = ApprovalGrid.DataKeys[row.RowIndex].Values["TargetYear"].ToString();
                string month = ApprovalGrid.DataKeys[row.RowIndex].Values["TARGET_MONTH"].ToString();

                //string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                if (chkItemSelect.Checked)
                {
                    Approve(branch, year, month, true);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
            BindData();
            Alert(msg);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                string branch = ApprovalGrid.DataKeys[row.RowIndex].Values["BranchID"].ToString();
                string year = ApprovalGrid.DataKeys[row.RowIndex].Values["TargetYear"].ToString();
                string month = ApprovalGrid.DataKeys[row.RowIndex].Values["TARGET_MONTH"].ToString();

                //string id = Convert.ToString(ApprovalGrid.DataKeys[row.RowIndex].Value.ToString());
                if (chkItemSelect.Checked)
                {
                    Approve(branch, year, month, false);
                }
            }
            msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
            BindData();
            Alert(msg);
        }

        private void Approve(string id, string year, string month, bool IsApprove)
        {
            string ActType;

            Shuba.Business.BranchTarget _BranchTarget = new Shuba.Business.BranchTarget();
            Shuba.Model.BranchTargetInfo bi = new Shuba.Model.BranchTargetInfo();

            bi = _BranchTarget.GetApprovalByID(id, year, month);
            ActType = bi.ActType;
            bi.UpdateBy = HttpContext.Current.User.Identity.Name;
            bi.UpdateDate = ProcessingDate();

            if (IsApprove)
            {
                _BranchTarget.Approve(id, year, month, ActType);
                AddLog("APPROVAL", "APPROVE BRANCH TARGET PLAN");
            }
            else
            {
                _BranchTarget.Reject(id, year, month);
                AddLog("APPROVAL", "REJECT BRANCH TARGET PLAN");
            }
        }

        private void InitClusterList(string RegionalID)
        {
            var _Cluster = new Shuba.Business.Cluster();

            ddlCluster.DataTextField = "ClusterName";
            ddlCluster.DataValueField = "ClusterID";
            ddlCluster.DataSource = _Cluster.GetListByRegion(RegionalID, Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);

            ddlCluster.DataBind();

            if (ddlCluster.Items.Count == 0)
            {
                ListItem ListAll = new ListItem();
                ListAll.Value = "";
                ListAll.Text = "";
                ddlCluster.Items.Insert(0, ListAll);
            }
        }

        private void InitRegionList()
        {
            var _Region = new Shuba.Business.Regional();

            ddlRegion.DataTextField = "RegionalName";
            ddlRegion.DataValueField = "RegionalID";
            ddlRegion.DataSource = _Region.GetList("%", Session["UnitID"].ToString(), HttpContext.Current.User.Identity.Name, ConfigurationManager.AppSettings["app.code"]);

            ddlRegion.DataBind();
        }

        protected void ddlRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            InitClusterList(ddlRegion.SelectedValue);
        }

        protected void ApprovalGrid_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[ApprovalGrid.Columns.Count - 3].Text.Replace(",", "").Trim() == "DELETE")
                {
                    e.Row.Cells[4].Text = "";
                }
            }
        }
    }   
 }

